<?php
/**
 * Controller_Catalog
 *
 * Класс Controller_Catalog отвечает за обработку страниц каталога товаров
 *
 * @author Mike
 */
class Controller_Catalog extends Controller_Base {

	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		$this->addCrumb('Главная', W_ABSPATH);
		switch ($this->arrRequest[1]) {
			case '':
				$this->actionCatalogMainPage();
				break;
			case 'men': case 'women':
				$this->data['sex'] = $this->arrRequest[1];
				$this->addCrumb($this->data['sex'] == 'women' ? 'Женщинам' : 'Мужчинам', W_ABSPATH . 'catalog/' . $this->data['sex']);
				
				if(!$this->arrRequest[2]) {
					$this->actionSexPage();
					break;
				}
				
				$fullUrl = trim(implode('/', array_slice($this->arrRequest, 2, count($this->arrRequest))), '/');
				
				$objProduct = new Product();
				$objProduct->find('first', array(
						'select' => '`product`.*, `brand`.`brand_name`, `brand`.`url` `brand_url`',
						'conditions' => "`product`.`full_url` = '" . Service_Escape::absolutelyEscapeString($fullUrl) . "' AND (`product`.`sex` = 2 OR `product`.`sex` = '" . ($this->data['sex'] == 'women' ? 0 : 1) . "')",
						'joins' => 'LEFT JOIN `brand` USING(`ID_brand`)'));
				if($objProduct->id) {
					$this->actionProductPage($objProduct);
					break;
				}
				
				$objCategory = new Category();
				$objCategory->find('first', array('conditions' => "`category`.`full_url` = '" . Service_Escape::absolutelyEscapeString($fullUrl) . "'"));
				if($objCategory->id) {
					$this->actionCategoryPage($objCategory);
					break;
				}
				
				// Проверяем на страницу бренда в рамках каталога
				$lastSlash = strrpos($fullUrl, '/');
				$brandUrl = substr($fullUrl, $lastSlash + 1);
				$catUrl = substr($fullUrl, 0, $lastSlash);
				
				$objProduct = new Product();
				$arrProducts = $objProduct->find('all', array(
					'select' => '`product`.*',
					'joins' => 'RIGHT JOIN `brand` USING(`ID_brand`) RIGHT JOIN `category` USING(ID_category)',
					'conditions' => "`brand`.`url`='" . $brandUrl . "' AND `category`.`full_url`='" . $catUrl . "'"
				));
				
				if(!empty($arrProducts)) $this->actionBrandPage($arrProducts);
				
				break;
			default:
				throw new Exception('', 404);
		}
	}
	
	/**
	 * Страница товара
	 *
	 * @param Product $objProduct - объект продукта
	 */
	public function actionProductPage(Product $objProduct) {
		$objCategory = new Category();
		
		$crumbBegin = $lastCrumbUrl = W_ABSPATH . 'catalog/' . $this->data['sex'];
		$arrCrumbs = $objCategory->getCategoryCrambs($objProduct->getField('ID_category'));
		foreach($arrCrumbs as $arrCrumb) {
			$this->addCrumb($arrCrumb['category_full_name'], $crumbBegin . '/' . $arrCrumb['full_url']);
		}
		$this->addCrumb($objProduct->getField('brand_name'), $crumbBegin . '/' . $arrCrumbs[count($arrCrumbs) - 1]['full_url'] . '/' . $objProduct->getField('brand_url'));
		$this->addCrumb($objProduct->getField('product_name'), $crumbBegin . '/' . $objProduct->getField('full_url'));
	
		$arrSizes = $objProduct->getAvailableSizes();				// Допустимые размеры товара
		$arrPhotos = $objProduct->getPhotosIds();					// Айдишники фотографий товара
		$arrReviews = $objProduct->getReviews();					// Отзывы товара
		$arrSimilarProducts = $objProduct->getSimilarProducts(4);	// Похожие товары
	
		$this->bodyAttr = 'product';
		$this->keywords = $objProduct->getField('meta_keywords');
		$this->description = $objProduct->getField('meta_description') ? $objProduct->getField('meta_description') : Service_TextMaker::getProductDescription($objProduct);
		$this->title = 'Купить ' . $objProduct->getField('product_name') . ', отзывы, цены и фотографии товара';
		$this->pageHead = $objProduct->getField('product_name') . (User_Seance::isAdmin() ? ' ' . '<a href="' . W_ADMIN . 'products/edit/' . $objProduct->id . '">(Редактировать)</a>' : '');
	
		$this->showHeader();
		View_Product::showProductPage($objProduct, $arrSizes, $arrPhotos, $arrReviews, $arrSimilarProducts);
		$this->showFooter();
	}

	/**
	 * Страница категории
	 *
	 * @param Category $objCategory- объект категории
	 */
	public function actionCategoryPage(Category $objCategory) {
		$crumbBegin = $lastCrumbUrl = W_ABSPATH . 'catalog/' . $this->data['sex'];
		$arrCrumbs = $objCategory->getCategoryCrambs();
		foreach($arrCrumbs as $arrCrumb) {
			$this->addCrumb($arrCrumb['category_full_name'], $crumbBegin . '/' . $arrCrumb['full_url']);
		}
		
		// Категории для вывода в левом меню
		//$this->data['left_categories'] = $objCategory->getCategoriesForLeft($objCategory->id);


		// Все продукты текущей категории
		$objProduct = new Product();
		$arrProducts = $objCategory->getCategoryProducts();
		
		$this->bodyAttr = 'category';
		$this->description = $objCategory->getField('meta_description');
		$this->keywords = $objCategory->getField('meta_keywords');
		$this->title = $objCategory->getField('category_full_name') . ' ' . ($this->data['sex'] == 'women' ? 'для женщин' : 'для мужчин');
		$this->pageHead = $this->title . (User_Seance::isAdmin() ? ' ' . '<a href="' . W_ADMIN . 'categories/edit/' . $objCategory->id . '">(Редактировать)</a>' : '');

		$this->showHeader();
			View_Category::showCategoryPage($objCategory, $arrProducts, $this->data['sex']);
		$this->showFooter();
	}
	
	/**
	 * Страницы всех товаров конкретного пола
	 *
	 */
	public function actionSexPage() {
		$objProduct = new Product();
		$objCategory = new Category();
		$arrProducts = $objProduct->find('all', array('conditions' => "`product`.`sex` = 1 OR `product`.`sex` = 2", 'order' => '`product`.`created_at` DESC')); 
		
		$this->bodyAttr = 'category';
		$this->description = '';
		$this->keywords = '';
		$this->title = '';
		$this->pageHead = '';
		
		$this->showHeader();
			View_Category::showCategoryPage($objCategory, $arrProducts, $this->data['sex']);
		$this->showFooter();
	}
	
	/**
	 * Страницы всех товаров конкретного брэнда в категории
	 *
	 */
	public function actionBrandPage(&$arrProducts) {
		$objCategory = new Category();
		$this->bodyAttr = 'category';
		$this->description = '';
		$this->keywords = '';
		$this->title = '';
		$this->pageHead = '';
	
		$this->showHeader();
		View_Category::showCategoryPage($objCategory, $arrProducts, $this->data['sex']);
		$this->showFooter();
	}
	
	/**
	 * Список всех категорий
	 *
	 */
	public function actionCatalogMainPage() {
		$this->showHeader();
		echo 'Курага';
		$this->showFooter();
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Controller_Base::showLeft()
	 */
	public function showLeft() {
		echo '<div id="left">';
			echo '<div class="cat-list sh-block">';
			foreach($this->data['left_categories'] as &$arrCategory) {
				View_Category::showCategory($arrCategory, false, 1, $this->data['sex']);
			}
			
			$objProductPropertyValue = new ProductPropertyValue(1);
			echo '<div class="by-propery">';
			echo '<a href="' . W_ABSPATH . 'properties/' . $objProductPropertyValue->getField('url') . '" class="branch stage1">Зимние кроссовки Nike</a>';
			echo '</div>';
			
			echo '</div>';
		echo '</div>';
	}
}